package com.qk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.qk.aop.anno.UseCache;
import com.qk.domain.business.BusinessCountDO;
import com.qk.domain.clue.ClueCountDO;
import com.qk.mapper.BusinessMapper;
import com.qk.mapper.ClueMapper;
import com.qk.service.ReportService;
import com.qk.vo.portal.ReportOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/16 15:57
 * @Description: 报表服务实现类
 */
@Service
@Slf4j
@SuppressWarnings("all")
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private StringRedisTemplate redisClient;

    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";

    @UseCache
    @Override
    public ReportOverviewVO getReport() {
        String key = StrBuilder.create(CACHE_PORTAL_KEY_PREFIX, "reportOverview").toString();
        String jsonStr = null;
        try {
            jsonStr = redisClient.opsForValue().get(key);
            if (StrUtil.isNotBlank(jsonStr)) {
                return JSONUtil.toBean(jsonStr, ReportOverviewVO.class);
            }
        } catch (Exception e) {
            log.error("redisClient.opsForValue().get(key) error: {}", e.getMessage());
        }
        ClueCountDO clueCountDO = clueMapper.selectClueCount();
        BusinessCountDO businessCountDO = businessMapper.selectBusinessCount();
        ReportOverviewVO vo = BeanUtil.copyProperties(clueCountDO, ReportOverviewVO.class);
        BeanUtil.copyProperties(businessCountDO, vo);
        try {
            redisClient.opsForValue().set(key, JSONUtil.toJsonStr(vo));
        } catch (Exception e) {
            log.error("redisClient.opsForValue().set(key, JSONUtil.toJsonStr(vo)) error: {}", e.getMessage());
        }
        return vo;
    }
}
